package com.blue.user.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.blue.user.service.LitCityService;
import com.litblue.common.utils.HttpClientUtils;
import com.litblue.common.utils.UserContext;
import com.litblue.starter.cache.redis.RedisCache;
import com.litblue.starter.cache.redis.RedisKeys;
import com.litblue.starter.core.AjaxResult;
import com.litblue.starter.pojo.user.dto.GetCityDto;
import com.litblue.starter.porperties.MapProperties;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
@AllArgsConstructor
public class LitCityServiceImpl implements LitCityService {

    private final MapProperties mapProperties;
    private final RedisCache redisCache;

    /**
     *
     * @param getCityDto
     * @return
     */
    @Override
    public AjaxResult getCityInfo(GetCityDto getCityDto) {
        String latitude = getCityDto.getLatitude();
        String longitude = getCityDto.getLongitude();
        Long userId = UserContext.getUser();
        List<Map> cityInfo=null;
//        redisKey
        RedisKeys redisKeys = RedisKeys.forCityMap(latitude, longitude, userId.toString());
        List<Map> cacheMap = redisCache.getCacheObject(RedisKeys.CITY_MAP_KEY);
        if (!CollectionUtil.isEmpty(cacheMap)){
            return new AjaxResult<>("获取成功","200",cacheMap);
        }

//        //GET请求
////周边推荐：boundary=nearby(lat,lng<中心坐标>,radius<半径/米>)
//        https://apis.map.qq.com/ws/place/v1/explore?boundary=nearby(40.040394,116.273523,1000)&policy=1&page_size=10&page_index=1&key=OB4BZ-D4W3U-*****
        String reqUrl=mapProperties.getPerimeterUrl();
        reqUrl= reqUrl+"?boundary=nearby("+latitude+","+longitude+","+mapProperties.getRadius()+")"+"&key="+mapProperties.getKey();
        try {
            String res = HttpClientUtils.doGet(reqUrl);
            JSONObject parse = JSONUtil.parseObj(res);
            Integer status = Integer.valueOf(parse.get("status").toString());

            if (status==0){
                 cityInfo = (List<Map>) parse.get("data");
                 redisCache.setCacheObject(RedisKeys.CITY_MAP_KEY,cityInfo);
                return new AjaxResult<>("获取成功","200",cityInfo);
            }else {
                return new AjaxResult<>("获取失败","500");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
